<template>
    <div style="padding: 10px 15px;" id="product">
        <el-card>
            <el-form ref="form" :model="form" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="店铺">
                            <el-select v-model="form.storeId" clearable size="mini" style="width: 100%">
                                <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName"
                                    :value="item.storeId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="SKU ID">
                            <el-input v-model="form.skuId" size="mini" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="SKC ID">
                            <el-input v-model="form.skcId" size="mini" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="类目">
                            <el-input v-model="form.item" size="mini" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item>
                            <el-button type="primary" size="mini" @click="handleClickSearch">查询</el-button>
                            <el-button type="primary" size="mini" @click="handleClickExport">导出Excel</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <el-card>
            <div class="table-container">
                <el-table :data="data" style="width: 100%" @sort-change="sortChange"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center">
                    </el-table-column>
                    <el-table-column width="120" align="center">
                        <template slot-scope="scope">
                            <el-image style="width: 100px; height: 100px" :src="scope.row.prodPictureUrl"
                                :preview-src-list="[scope.row.prodPictureUrl]" fit="fit"></el-image>
                            <span>￥{{ scope.row.cny }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品详情" align="center">
                        <template slot-scope="scope">
                            <div style="display: flex;flex-direction: column;font-size: 14px;align-items: flex-start">
                                <div><span style="font-weight: 600;">店铺：</span>{{ scope.row.shopName }}</div>
                                <div><span style="font-weight: 600;">商品类别：</span>{{ scope.row.prodClassify }}</div>
                                <div style="display: flex;">
                                    <div style="font-weight: 600;width: 70px;">商品描述：</div>
                                    <div
                                        style="width: 200px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                                        <el-tooltip placement="top" effect="light">
                                            <div slot="content">{{ scope.row.prodDescription }}</div>
                                            <div>{{ scope.row.prodDescription }}</div>
                                        </el-tooltip>
                                    </div>
                                </div>
                                <div><span style="font-weight: 600;">Skc Id：</span>{{ scope.row.skcId }}</div>
                                <div><span style="font-weight: 600;">Sku Id：</span>{{ scope.row.skuId }}</div>
                                <div><span style="font-weight: 600;">商品标记：</span>{{ scope.row.prodMark }}</div>
                                <div><span style="font-weight: 600;">类目：</span>{{ scope.row.item }}</div>
                                <div><span style="font-weight: 600;">入站时长：</span>{{ scope.row.onSalesDurationOffline }}
                                </div>
                                <div><span style="font-weight: 600;">是否JIT：</span>
                                    <el-tag v-if="scope.row.suggestCloseJit == 'true'" size="mini"
                                        type="success">JIT</el-tag>
                                    <span v-if="scope.row.suggestCloseJit == 'false'">-</span>
                                </div>
                                <div><span style="font-weight: 600;">备注：</span>{{ scope.row.remark }}</div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="库存" align="center">
                        <el-table-column prop="uasgeInventory" label="仓内可用" width="100" align="center">
                        </el-table-column>
                        <el-table-column prop="unusageInventory" label="仓内不可用" width="100" align="center">
                        </el-table-column>
                        <el-table-column prop="deliveredInventory" label="已发库存" width="100" align="center">
                        </el-table-column>
                    </el-table-column>
                    <el-table-column label="销量" align="center">
                        <el-table-column prop="saleDataToday" label="今日" width="100" sortable="custom" align="center">
                        </el-table-column>
                        <el-table-column prop="saleDataWeek" label="近7天" width="100" sortable="custom" align="center">
                        </el-table-column>
                        <el-table-column prop="saleDataMonth" label="近30天" width="100" sortable="custom" align="center">
                        </el-table-column>
                    </el-table-column>
                    <el-table-column label="操作" width="120px" align="center">
                        <template slot-scope="scope">
                            <div>
                                <el-button size="mini" type="primary" style="width:90px;"
                                    @click="handleClickItem(scope.row.skcId)">录入类目</el-button>
                                <el-button size="mini" type="primary"
                                    style="width:90px;margin-left:0px;margin-top:10px;"
                                    @click="handleClickRemark(scope.row.skcId)">备注</el-button>
                                <el-button size="mini" type="primary"
                                    style="width:90px;margin-left:0px;margin-top:10px;"
                                    @click="handleClickApply">申请备货</el-button>
                                <el-button size="mini" type="primary"
                                    style="width:90px;margin-left:0px;margin-top:10px;"
                                    @click="handleClickDetail(scope.row.skcId)">备货详情</el-button>
                                <el-button size="mini" type="primary"
                                    style="width:90px;margin-left:0px;margin-top:10px;"
                                    @click="handleClickPicAbout(scope.row.skcId)">相关图纸</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-pagination background :current-page.sync="pagination.current" @size-change="handleSizeChange"
                :page-sizes="[10, 20, 30, 40, 50]" :page-size="pagination.pageSize"
                @current-change="handleCurrentChange" layout="total, sizes, next, pager, prev"
                :total="pagination.total">
            </el-pagination>
        </el-card>

        <!-- 添加备注 -->
        <el-dialog title="添加备注" :visible.sync="dialogVisibleRemark" width="50%" :close-on-click-modal="false">
            <el-row>
                <el-col :span="24">
                    <el-input type="textarea" :rows="2" v-model="remark" size="small" clearable></el-input>
                </el-col>
            </el-row>
            <div style="text-align: center;padding: 15px;">
                <el-button type="primary" size="mini" class="cus-submit-btn" native-type="submit"
                    @click.native.prevent="handleInputRemark">确认</el-button>
            </div>
        </el-dialog>

        <!-- 修改类目 -->
        <el-dialog title="录入类目" :visible.sync="dialogVisibleItem" width="50%" :close-on-click-modal="false">
            <el-row>
                <el-col :span="24">
                    <el-input type="textarea" :rows="2" v-model="remark" size="small" clearable></el-input>
                </el-col>
            </el-row>
            <div style="text-align: center;margin-top: 10px;">
                <el-button type="primary" size="mini" class="cus-submit-btn" native-type="submit"
                    @click.native.prevent="handleInputItem">确认</el-button>
            </div>
        </el-dialog>

        <!-- 相关图片 -->
        <el-dialog title="相关图片" :visible.sync="dialogVisibleImage" width="50%" :close-on-click-modal="false">
            <div style="display: flex;flex-direction:column">
                <ul>
                    <li v-for="item in imageList" :key="item.id">{{ item.filename }} <span class="fileImage"
                            @click="handleDeleteImage(item.id)"
                            style="color: red;margin-left: 20px;cursor: pointer;">删除</span>
                    </li>
                </ul>
            </div>
            <el-upload ref="uploadPic" action="#" class="upload-demo" list-type="picture-card" multiple
                :file-list="fileList" :auto-upload="false" :on-change="handleUploadChange"
                accept=".jpg,.gif,.png,.jpeg">
                <i class="el-icon-plus"></i>
            </el-upload>
            <div style="padding: 10px 0px;text-align: right;">
                <el-button type="primary" size="small" @click="handleSubmitUpload">上传</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import API from "../../api";
export default {
    name: 'ProductManagementInfo',
    data() {
        return {
            dataLoading: false,
            data: [],
            storeList: [],
            form: {
                storeId: '',
                skuId: '',
                skcId: '',
                item: ''
            },
            productForm: {
                deliveredInventory: "",
                item: "",
                prodClassify: "",
                prodDescription: "",
                prodMark: "",
                prodPictureUrl: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg",
                saleDataMonth: "133",
                saleDataToday: "4",
                saleDataWeek: "14",
                skcId: "1232143",
                spuId: "12432423",
                storeName: "南风小铺OL轻复古女包",
                unusageInventory: "",
                usageInventory: ""
            },
            rules: {
                storeName: [{ required: true, message: "请输入账号", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
            },
            // 与pagination对齐
            pagination: {
                pageSize: 20,
                total: 0,
                current: 1,
            },
            imageList: [],
            remark: "",
            skcId_temp: "",
            searchValue: '',
            fileList: [],
            multipleSelection: [],
            sortField: "",
            sortOrder: "",
            importFormData: "",
            dialogVisibleItem: false,
            dialogVisibleRemark: false,
            dialogVisibleImage: false
        };
    },
    computed: {
    },
    mounted() {
        //查询店铺数据
        this.searchStoreData();
        // 查询商品数据
        this.searchData();
    },

    methods: {
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(val);
        },
        searchStoreData() {
            API.send("queryStore").then(async (res) => {
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    return;
                }
                this.storeList = res.data;
            })
        },
        searchImageData(id) {
            API.send("findFilesBySkcId", { data: { skcId: id } }).then(async (res) => {
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    return;
                }
                this.imageList = res.data.fileList;
            })
        },
        searchData() {
            const loading = this.$loading({
                lock: true,
                text: this.$t('loading.login'),
                spinner: 'el-icon-loading',
            });
            const req = {
                data: {
                    ...this.form,
                    pageNum: this.pagination.current,
                    pageSize: this.pagination.pageSize
                }
            }
            API.send("getProductList", req).then(async (res) => {
                console.log(res)
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    loading.close();
                    return;
                }
                this.data = res.data.list;
                this.pagination.total = res.data.total;
                this.goTop();
                loading.close();
            })
        },
        handleClickSearch() {
            this.searchData();
        },
        handleClickExport() {
            if (this.multipleSelection.length <= 0) {
                this.ExportExcelByCondition();
            } else {
                this.ExportExcel();
            }
        },
        ExportExcel() {
            const loading = this.$loading({
                lock: true,
                text: this.$t('loading.login'),
                spinner: 'el-icon-loading',
            });
            let dataList = [];
            this.multipleSelection.forEach((item,index) => {
                let obj = {
                    deliveredInventory: item.deliveredInventory,
                    item: item.item,
                    onSalesDurationOffline: item.onSalesDurationOffline,
                    pictureUrl: item.prodPictureUrl,
                    price: item.cny,
                    proClassify: item.prodClassify,
                    prodDescription: item.prodDescription,
                    remark: item.remark,
                    saleDataMonth: item.saleDataMonth,
                    saleDataToday: item.saleDataToday,
                    saleDataWeek: item.saleDataWeek,
                    skcId: item.skcId,
                    skuId: item.skuId,
                    srlNo: index + 1,
                    storeName: item.shopName,
                    suggestCloseJit: item.suggestCloseJit ? "JIT" : "-",
                    uasgeInventory: item.uasgeInventory,
                    unusageInventory: item.unusageInventory
                }
                dataList.push(obj);
            })
            const req = {
                data: {
                    dataList: dataList
                }
            }
            API.send("exportProductExcel", req).then(async (res) => {
                loading.close();
                if (res.data.type == 'application/json') {
                    this.$message.error("下载失败！");
                } else {
                    const url = window.URL.createObjectURL(new Blob([res.data]));
                    const a = document.createElement("a");
                    a.style.display = "none";
                    a.href = url;
                    a.download = "ProductsData.xls";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
            }).catch((err) => {
                loading.close();
                console.log(err);
                this.$message.error("导出异常！");
            });
        },
        ExportExcelByCondition() {
            const loading = this.$loading({
                lock: true,
                text: this.$t('loading.login'),
                spinner: 'el-icon-loading',
            });
            const req = {
                data: {
                    ...this.form,
                    sortField: this.sortField,
                    sortOrder: this.sortOrder
                }
            }
            API.send("exportProductExcelByCondition", req).then(async (res) => {
                loading.close();
                if (res.data.type == 'application/json') {
                    this.$message.error("下载失败！");
                } else {
                    const url = window.URL.createObjectURL(new Blob([res.data]));
                    const a = document.createElement("a");
                    a.style.display = "none";
                    a.href = url;
                    a.download = "ProductsData.xls";
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
            }).catch((err) => {
                loading.close();
                console.log(err);
                this.$message.error("导出异常！");
            });
        },
        handleClickRemark(id) {
            this.dialogVisibleRemark = true;
            this.skcId_temp = id;
        },
        handleClickApply() {
            window.open('https://seller.kuajingmaihuo.com/main/sale-manage/main');
        },
        handleClickDetail(id) {
            this.$router.push({ path: '/stock/index', query: { skcId: id } });
        },
        handleClickItem(id) {
            this.dialogVisibleItem = true;
            this.skcId_temp = id;
        },
        handleInputRemark() {
            this.$confirm('确认提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: this.$t('loading.login'),
                    spinner: 'el-icon-loading',
                });
                API.send("addProRemark", {
                    data: {
                        remark: this.remark,
                        skcId: this.skcId_temp
                    }
                }).then(async (res) => {
                    if (res.code !== 200) {
                        this.$message({
                            type: 'error',
                            message: '添加失败!'
                        });
                        loading.close();
                        return;
                    }
                    this.searchData();
                    this.remark = "";
                    this.dialogVisibleRemark = false;
                    loading.close();
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                })
            }).catch(() => {
                loading.close();
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        handleInputItem() {
            this.$confirm('确认提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: this.$t('loading.login'),
                    spinner: 'el-icon-loading',
                });
                API.send("modifyItem", {
                    data: {
                        item: this.remark,
                        skcId: this.skcId_temp
                    }
                }).then(async (res) => {
                    if (res.code !== 200) {
                        this.$message({
                            type: 'error',
                            message: '添加失败!'
                        });
                        loading.close();
                        return;
                    }
                    this.searchData();
                    this.remark = "";
                    this.dialogVisibleItem = false;
                    loading.close();
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                })
            }).catch(() => {
                loading.close();
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        handleClickPicAbout(id) {
            this.dialogVisibleImage = true;
            this.skcId_temp = id;
            this.searchImageData(id);
        },
        handleUploadChange(file, fileList) {
            this.importFormData = new FormData();
            fileList.forEach(item => {
                this.importFormData.append("files", item.raw);
            });
        },
        handleSubmitUpload() {
            if (this.$refs.uploadPic.uploadFiles.length <= 0) {
                this.$message({
                    type: 'error',
                    message: "图片为空，请先选择图片！"
                });
                return;
            }
            this.$confirm('确认提交?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: this.$t('loading.login'),
                    spinner: 'el-icon-loading',
                });
                this.importFormData.append("skcId", this.skcId_temp);
                API.send("uploadFile", {
                    data: {
                        files: this.importFormData.getAll('files'),
                        skcId: this.importFormData.get('skcId')
                    }
                }).then(async (res) => {
                    if (res.code !== 200) {
                        this.$message({
                            type: 'error',
                            message: '添加失败!'
                        });
                        loading.close();
                        return;
                    }
                    this.searchData();
                    this.fileList = [];
                    this.dialogVisibleImage = false;
                    loading.close();
                    this.$message({
                        type: 'success',
                        message: '添加成功!'
                    });
                })
            }).catch(() => {
                loading.close();
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val;
            this.searchData();
        },
        handleCurrentChange(val) {
            this.pagination.current = val;
            this.searchData();
        },
        handleDeleteImage(id) {
            this.$confirm('确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const loading = this.$loading({
                    lock: true,
                    text: this.$t('loading.login'),
                    spinner: 'el-icon-loading',
                });
                API.send("deleteFile", {
                    data: {
                        id: id
                    }
                }).then(async (res) => {
                    if (res.code !== 200) {
                        this.$message({
                            type: 'error',
                            message: '删除失败!'
                        });
                        loading.close();
                        return;
                    }
                    this.searchImageData(this.skcId_temp);
                    loading.close();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                })
            }).catch(() => {
                loading.close();
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        sortChange(obj) {
            this.sortField = "";
            this.sortOrder = "";
            obj.order == "descending" ? this.sortOrder = "DESC" : this.sortOrder = "ASC";
            if (obj.prop == "saleDataToday") this.sortField = "sale_data_today";
            if (obj.prop == "saleDataWeek") this.sortField = "sale_data_week";
            if (obj.prop == "saleDataMonth") this.sortField = "sale_data_month";
            const req = {
                data: {
                    ...this.form,
                    sortField: this.sortField,
                    sortOrder: this.sortOrder,
                    pageNum: this.pagination.current,
                    pageSize: this.pagination.pageSize
                }
            }
            API.send("getProductList", req).then(async (res) => {
                console.log(res)
                if (res.code !== 200) {
                    this.$message.error(res.msg);
                    return;
                }
                this.data = res.data.list;
                this.pagination.total = res.data.total;
                this.goTop();
            })
        },
        //点击置顶
        goTop() {
            const scrollEle = document.querySelector('#product');
            scrollEle.scrollIntoView({ behavior: "smooth" })
        }
    },
};
</script>

<style lang="scss" scoped>
#product {
    position: relative;
}

.payment-col {
    display: flex;

    .trend-container {
        display: flex;
        align-items: center;
        margin-left: 8px;
    }
}

.table-container {
    padding-block: 10px;
}

.left-operation-container {
    padding: 0 0 6px 0;
    margin-bottom: 16px;

    .selected-count {
        display: inline-block;
        margin-left: 10px;
    }
}

.cardBox:hover {
    transform: scale(1.05, 1.05);
}

.search-input {
    width: 360px;
    margin-top: 16px;
}

::v-deep .el-dialog__body {
    padding: 0px 20px;
}

::v-deep .el-card__header {
    padding: 8px 20px;
}

::v-deep .el-card__body {
    padding: 10px 20px;
}

::v-deep .el-form-item {
    margin-bottom: 0px;
}

::v-deep .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
}

::v-deep .el-pagination {
    .el-pagination__total {
        float: left;
    }

    .btn-prev,
    .el-pager,
    .btn-next {
        float: right;
    }
}
</style>
